import { createStore, Commit } from 'vuex'
import axios from 'axios';

export interface ResponseType<P = { [key: string]: any }> {
  code: number;
  msg: string;
  data: P;
}
export interface UserProps {
  isLogin: boolean;
  nickName?: string;
  _id?: string;
  column?: string;
  email?: string;
  avatar?: ImageProps;
  description?: string;
}
export interface ImageProps {
  _id?: string;
  url?: string;
  createdAt?: string;
  fitUrl?: string;
}
export interface ColumnProps {
  _id: string;
  title: string;
  avatar?: ImageProps;
  description: string;
}
export interface PostProps {
  _id?: string;
  title: string;
  excerpt?: string;
  content?: string;
  image?: ImageProps | string;
  createdAt?: string;
  column: string;
  author?: string;
}
export interface GlobalErrorProps {
  status: boolean;
  message?: string;
}
export interface GlobalDataProps {
  token: string;
  error: GlobalErrorProps;
  loading: boolean;
  columns: ColumnProps[];
  posts: PostProps[];
  user: UserProps;
}
const getAndCommit = async (url: string, mutationName: string, commit: Commit) => {
  const { data } = await axios.get(url)
  commit(mutationName, data)
  return data
}
const postAndCommit = async (url: string, mutationName: string, commit: Commit, payload: any) => {
  const { data } = await axios.post(url, payload)
  commit(mutationName, data)
  return data
}

export default createStore<GlobalDataProps>({
  state: {
    error: { status: false },
    token: localStorage.getItem('token') || '',
    loading: false,
    columns: [],
    posts: [],
    user: { isLogin: false },
  },
  getters: {
    getColumnById(state) {
      return function (id: string) {
        return state.columns.find(c => c._id == id)//find返回对象
      }
    },
    getPostsById(state) {
      return function (cid: string) {
        return state.posts.filter(post => post.column == cid)//filter返回数组
      }
    },
    getCurrentPost: (state) => (id: string) => {
      return state.posts.find(post => post._id === id)
    }
  },
  mutations: {
    // login(state) {
    //   state.user = { ...state.user, isLogin: true, name: '大白' }
    // },
    createPost(state, newPost) {
      state.posts.push(newPost)
    },
    fetchColumns(state, res) {
      state.columns = res.data.list
      console.log(res);
    },
    fetchColumn(state, res) {
      state.columns = [res.data]
      console.log(res.data);
    },
    fetchPosts(state, res) {
      state.posts = res.data.list
      console.log(res);
    },
    fetchPost(state, rawData) {
      state.posts = [rawData.data]
    },
    setLoading(state, status) {
      state.loading = status
    },
    setError(state, e: GlobalErrorProps) {
      state.error = e
    },
    fetchCurrentUser(state, res) {
      state.user = { isLogin: true, ...res.data }
    },
    login(state, res) {
      const token = res.data.token
      state.token = token
      localStorage.setItem('token', token)
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
    },
    logout(state) {
      state.token = ''
      localStorage.remove('token')
      delete axios.defaults.headers.common.Authorization
    }
  },

  actions: {
    //首页显示column
    fetchColumns({ commit }) {
      return getAndCommit('columns', 'fetchColumns', commit)
    },
    // fetchColumns({commit}){
    //   axios.get('columns').then(res=>{
    //     commit('fetchColumns',res.data)
    //   })
    // },

    //专栏详情column
    // fetchColumn({ commit }, cid) {
    //   axios.get(`/columns/${cid}`).then(res => {
    //     commit('fetchColumn', res.data)
    //   })
    // },
    fetchColumn({ commit }, cid) {
      return getAndCommit(`/columns/${cid}`, 'fetchColumn', commit)
    },

    //专栏详情post
    fetchPosts({ commit }, cid) {
      return getAndCommit(`/columns/${cid}/posts`, 'fetchPosts', commit)
    },
    fetchPost({ commit }, id) {
      return getAndCommit(`/posts/${id}`, 'fetchPost', commit)
    },
    fetchCurrentUser({ commit }) {
      return getAndCommit('/user/current', 'fetchCurrentUser', commit)
    },

    // login({ commit }, payload) {
    //   return axios.post('/user/login', payload).then(res => {
    //     commit('login', res.data)
    //   })
    // }
    login({ commit }, payload) {
      return postAndCommit('/user/login', 'login', commit, payload)
    },
    // createPost({ commit }, payload) {
    //   return postAndCommit('/posts','createpost', commit, payload)
    // },
    createPost({ commit }, payload) {
      return new Promise((resolve) => {
        axios.post('/posts', payload).then(res => {
          commit('createpost', res.data)
        })
      })
    },
    loginAndFetch({ dispatch }, loginData) {
      return dispatch('login', loginData).then(() => {
        return dispatch('fetchCurrentUser')
      })
    }
  },
  modules: {
  },
})
